package com.chenfan.filestore.disruptor.handler;

import com.alibaba.fastjson.JSONObject;
import com.chenfan.ccp.common.exception.ApiException;
import com.chenfan.ccp.common.result.R;
import com.chenfan.filestore.exception.FileStoreCode;
import com.chenfan.filestore.model.BatchImportTemplate;
import com.chenfan.filestore.model.dto.ParseExcelDTO;
import com.chenfan.filestore.vo.ImportResultVO;
import com.chenfan.infra.constants.CommonBeanConstants;
import com.chenfan.infra.context.UserContextHolder;
import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author K
 * @date 2023/6/5 4:12 PM
 * 将Excel数据转换为业务数据
 */
@Component
@Slf4j
public class TransferBusinessDataHandler implements EventHandler<ParseExcelDTO> {
    public static final String ROW_INDEX = "rowIndex";

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Resource
    private RestTemplate restTemplate;

    @Override
    public void onEvent(ParseExcelDTO parseExcelDTO, long l, boolean b) {
    }

    public ParseExcelDTO getList(ParseExcelDTO parseExcelDTO) {
        List<ImportResultVO> rs = sendToBusiness(parseExcelDTO);
        parseExcelDTO.setResultList(rs);
        return parseExcelDTO;
    }

    private List<ImportResultVO> sendToBusiness(ParseExcelDTO parseExcelDTO) {
        List<Map<String, Object>> sendToBusinessList = parseExcelDTO.getSendToBusinessList();
        BatchImportTemplate template = parseExcelDTO.getBatchImportTemplate();
        String callbackUrl = template.getCallbackUrl();
        log.info("开始请求接口:{}, 请求参数:{}", callbackUrl, JSONObject.toJSONString(sendToBusinessList));

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        httpHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        httpHeaders.add("Authorization", UserContextHolder.getToken());
        if (Objects.nonNull(UserContextHolder.getUserVo())) {
            httpHeaders.add(CommonBeanConstants.TENANT_ID, UserContextHolder.getUserVo().getTenantId().toString());
        }
        HttpEntity<List<Map<String, Object>>> formEntity = new HttpEntity<>(sendToBusinessList, httpHeaders);

        // 拿到服务名称.
        String[] split = callbackUrl.split(":");
        if (split.length != 2) {
            throw new ApiException(FileStoreCode.BASE_PRINT_TEMPLATE_URL_WRONG);
        }
        String serviceName = split[0];
        String uri = split[1];
        ServiceInstance t = loadBalancerClient.choose(serviceName);
        // 找不到对应的服务
        if (t == null) {
            throw new ApiException(FileStoreCode.BASE_PRINT_TEMPLATE_BUSINESS_ERROR);
        }

        String url = String.format("http://%s:%s", t.getHost(), t.getPort());
//        String url = "http://10.228.81.198:8081/chenfan_base";

        try {
            ResponseEntity<com.chenfan.ccp.common.result.R> responseData = restTemplate.postForEntity(url + uri, formEntity, com.chenfan.ccp.common.result.R.class);
            log.info("请求结果结束, 结果:{}", JSONObject.toJSONString(responseData));
            R<List<ImportResultVO>> r = responseData.getBody();

            if (r.getCode() != 0 && r.getCode() != 200) {
                return sendToBusinessList.stream().map(e -> {
                    ImportResultVO importResultVO = new ImportResultVO();
                    Object o = e.get(ROW_INDEX);
                    importResultVO.setRowIndex(Integer.parseInt(String.valueOf(o)));
                    importResultVO.setFailReason("业务异常");
                    return importResultVO;
                }).collect(Collectors.toList());
            }

            return JSONObject.parseArray(JSONObject.toJSONString(r.getObj()), ImportResultVO.class);
        } catch (Exception x) {
            log.error("请求业务异常:{}", x.getMessage());
            return sendToBusinessList.stream().map(e -> {
                ImportResultVO importResultVO = new ImportResultVO();
                Object o = e.get(ROW_INDEX);
                importResultVO.setRowIndex(Integer.parseInt(String.valueOf(o)));
                importResultVO.setFailReason("业务异常");
                return importResultVO;
            }).collect(Collectors.toList());
        }

    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder){
        return builder.build();
    }
}
